<template>
  <div v-loading="handleLoading">
    <el-form
      ref="handleForm"
      :model="handleForm"
      :rules="handleRules"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="name" label="角色名称">
            <el-input
              v-model="handleForm.name"
              placeholder="请输入角色名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="permission" label="权限(key)">
            <el-input
              v-model="handleForm.permission"
              placeholder="请输入权限(key)"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="level" label="角色级别">
            <el-select
              v-model="handleForm.level"
              placeholder="请选择角色级别"
              clearable
            >
              <el-option
                v-for="item in levelList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="dataScope" label="角色领域">
            <el-input
              v-model="handleForm.dataScope"
              placeholder="请输入角色领域"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="menus" label="菜单">
            <el-cascader
              v-model="handleForm.menus"
              placeholder="请选择菜单"
              :options="menuList"
              collapse-tags
              :props="deptOptions"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item prop="remark" label="角色描述">
        <el-input
          v-model="handleForm.remark"
          placeholder="请输入角色描述"
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <div class="btns btn-right-container">
      <el-button type="normal" size="medium" @click="$emit('closeDialog', false)">
        关闭
      </el-button>
      <el-button type="primary" size="medium" @click="saveInfo">
        保存
      </el-button>
    </div>
  </div>
</template>
<script>
import { addRoles, editRoles } from '@/api/roles'
export default {
  name: 'RolestHandle',
  props: {
    action: {
      type: String,
      default: 'add'
    },
    formData: {
      type: Object,
      default: () => ({})
    },
    level: {
      type: [Number, String],
      default: ''
    },
    levelList: {
      type: Array,
      default: () => []
    },
    menuList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      handleLoading: false,
      handleForm: {
        name: '',
        level: '',
        dataScope: '',
        permission: '',
        remark: '',
        menus: []
      },
      handleRules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        level: [{
          required: true, message: '请选择角色级别', trigger: 'change'
        }],
        permission: [{
          required: true, message: '权限类型(key)不能为空', trigger: 'blur'
        }],
        menus: [{
          required: true, message: '请选择菜单', trigger: 'change'
        }]
      },
      deptOptions: { // 菜单级联参数
        label: 'name',
        value: 'id',
        children: 'children',
        // checkStrictly: true,
        multiple: true
      }
    }
  },
  created() {
    console.log(this.formData, this.menuList.sort((a, b) => {
      if (a.id > 70 || b.id > 70) {
        console.log(a, b)
      }
      return a.id - b.id
    }))
    if (this.action == 'edit') {
      this.initHandleForm()
    }
  },
  methods: {
    saveInfo() {
      console.log(this.handleForm)
      this.$refs.handleForm.validate((valid) => {
        if (!valid) return
        this.handleLoading = true
        let fn = addRoles
        const param = {
          ...this.handleForm,
          enabled: true
        }
        param.menus = Array.from(param.menus.reduce((o, n) => {
          n.forEach(id => {
            o.add(id)
          })
          return o
        }, new Set())).sort((a, b) => a - b).map(menu => { return { id: menu } })
        if (this.action == 'edit') {
          fn = editRoles
          param.id = this.formData.id
        }
        console.log(param)
        fn(param).then(() => {
          this.$message({
            message: `${this.action == 'add' ? '新增' : '修改'}成功`,
            type: 'success'
          })
          this.$emit('closeDialog', true)
        }).catch((err) => {
          const errInfo = err.response && err.response.request.responseText ? JSON.parse(err.response.request.responseText) : ''
          this.$message({
            message: errInfo ? errInfo.message : `${this.action == 'add' ? '新增' : '修改'}失败`,
            type: 'error'
          })
        }).finally(() => {
          this.handleLoading = false
        })
      })
    },
    initHandleForm() {
      Object.keys(this.handleForm).forEach(key => {
        this.handleForm[key] = this.formData[key]
      })
      const typeOne = []
      const typeTwo = []
      const typeThree = []
      const typeOther = []
      this.formData['menus'].forEach(menu => {
        if (menu.id >= 70) {
          console.log('menu---', menu)
        }
        switch (menu.type) {
          case 0:
            typeOne.push(menu)
            break
          case 1:
            typeTwo.push(menu)
            break
          case 2:
            typeThree.push(menu)
            break
          default:
            typeOther.push(menu)
            break
        }
      })
      console.log(typeOther)
      typeThree.forEach(t3 => {
        typeTwo.forEach(t2 => {
          if (t2.id === t3.pid) {
            if (!t2.children) {
              t2.children = []
            }
            t2.children.push(t3)
          }
        })
      })
      typeTwo.forEach(t2 => {
        if (t2.id > 70) {
          console.log('t2', t2)
        }
        typeOne.forEach(t1 => {
          if (t1.id === t2.pid) {
            if (!t1.children) {
              t1.children = []
            }
            t1.children.push(t2)
          }
        })
      })
      function getRes(list) {
        const result = []
        function deepRes(childList, parentNode) {
          childList.forEach(child => {
            if (child.id >= 70) {
              console.log(child)
            }
            const childs = parentNode ? parentNode.concat(child.id) : [child.id]
            result.push(childs)
            if (child.children) {
              deepRes(child.children, childs)
            }
          })
        }
        deepRes(list, '')
        return result
      }
      const menussss = getRes(typeOne)
      console.log(menussss, typeOne)
      this.handleForm['menus'] = menussss
      this.$nextTick(() => {
        this.$refs.handleForm.clearValidate()
      })
    }
  }
}
</script>
